package com.lst.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.OnlineCourseListReqPara;
import com.lst.entity.response.OnlineCourseListResPara2;
import com.lst.model.CourseAction;
import com.lst.model.OnlineCourse;
import com.lst.model.VideoMusic;
import com.lst.service.CourseActionService;
import com.lst.service.OnlineCourseService;
import com.lst.service.VideoMusicService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

public class SpeciallyRunServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private OnlineCourseService onlineCourseService = ctx.getBean(OnlineCourseService.class);
	
	private VideoMusicService videoMusicService = ctx.getBean(VideoMusicService.class);
	
	private CourseActionService courseActionService = ctx.getBean(CourseActionService.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		OnlineCourseListResPara2 resPara = new OnlineCourseListResPara2();
		try {
			OnlineCourseListReqPara reqPara = getReqPara(request);

			if (isCheckField(reqPara, resPara)) {
			//	    Integer userid = Integer.valueOf(reqPara.getUserid());	
				    Integer type = Integer.valueOf(reqPara.getType());	
				    Integer ability = Integer.valueOf(reqPara.getAbility());	
				    String level=reqPara.getLevel();
				    
				    Map<String,Object> map=new HashMap<String,Object>();
					map.put("runType", type);
					map.put("trainType", ability);
					map.put("courseNo", level);
					List<OnlineCourse> list=onlineCourseService.queryList2(map);
					if(list!=null&&list.size()>0){
						Random rand = new Random();
						int num=rand.nextInt(list.size());
						OnlineCourse onlinecourse=list.get(num); 
						
	                    	onlinecourse.setTips(CommFunUtils.formatStr(onlinecourse.getTips(), "• ", "\r\n"));
	    					onlinecourse.setCourseno(CommFunUtils.formatStr(onlinecourse.getCourseno(), "• ", "\r\n"));
	    					onlinecourse.setCalorie(onlinecourse.getCalorie().setScale(0));
	    					onlinecourse.setCalorieStr(onlinecourse.getCalorie().setScale(0).toString() + "千卡");
	    					onlinecourse.setCalorieStr(CommFunUtils.formatStr(onlinecourse.getCalorieStr(), "• ", "\r\n"));
	    					onlinecourse.setIntroduction(CommFunUtils.formatStr(onlinecourse.getIntroduction(), "• ", "\r\n"));
	    					onlinecourse.setPeople(CommFunUtils.formatStr(onlinecourse.getPeople(), "• ", "\r\n"));
	    					onlinecourse.setDescript(CommFunUtils.formatStr(onlinecourse.getDescript(), "• ", "\r\n"));
	    					onlinecourse.setActionname(CommFunUtils.formatStr(onlinecourse.getActionname(), "• ", "\r\n"));
	    					onlinecourse.setCycle(CommFunUtils.formatStr(onlinecourse.getCycle(), "• ", "\r\n"));
	    					onlinecourse.setNotice(CommFunUtils.formatStr(onlinecourse.getNotice(), "• ", "\r\n"));

	    					List<CourseAction> actionList=courseActionService.queryByList(onlinecourse.getId());//动作列表
	    					if(actionList!=null&&actionList.size()>0){
	    						for(CourseAction courseAction:actionList){
	    						List<VideoMusic> videoMusicList=videoMusicService.queryByList(courseAction.getActionId());
	    						courseAction.setVideoMusicList(videoMusicList);
	    						}
	    					}
	    					onlinecourse.setCourseActionList(actionList);
	    					resPara.setOnlinecourse(onlinecourse);	
	    					resPara.setCode(CommCode.M_Y000000);
	        				resPara.setMessage(CommCode.M_Y000001);
					}else{
	                    	resPara.setCode(CommCode.M_A000000);
	        				resPara.setMessage("此等级课程不存在，请重新选择条件");
					}
			}
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
			logger.info(jsonResult);

			logger.info("OnlineCourseDetailServlet jsonResult: " + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public OnlineCourseListReqPara getReqPara(HttpServletRequest request) {

		OnlineCourseListReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request,new OnlineCourseListReqPara());

			reqPara = (OnlineCourseListReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String type = request.getParameter("type");
			String level = request.getParameter("level");
			String ability = request.getParameter("ability");

			logger.info("reqPara userid: " + userid);
			logger.info("reqPara type: " + type);
			logger.info("reqPara level: " + level);
			logger.info("reqPara ability: " + ability);

			reqPara.setUserid(userid);
			reqPara.setType(type);
			reqPara.setLevel(level);
			reqPara.setAbility(ability);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}
		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		OnlineCourseListReqPara ocReqPara = (OnlineCourseListReqPara) reqPara;
		OnlineCourseListResPara2 ocResPara = (OnlineCourseListResPara2) resPara;

		if (StringUtils.isEmpty(ocReqPara.getType())) {
			ocResPara.setCode(CommCode.M_A000000);
			ocResPara.setMessage("课程类型为空");
		}else if (StringUtils.isEmpty(ocReqPara.getLevel())) {
			ocResPara.setCode(CommCode.M_A000000);
			ocResPara.setMessage("课程等级为空");
		}else if (StringUtils.isEmpty(ocReqPara.getAbility())) {
			ocResPara.setCode(CommCode.M_A000000);
			ocResPara.setMessage("训练能力为空");
		}else {
			flag = true;
		}
		return flag;
	}
}
